package com.chen.palmar.project.producer;

import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.chen.palmar.R;
import com.chen.palmar.base.BaseActivity;
import com.chen.palmar.common.datasource.DataCenter;
import com.chen.palmar.common.override.HttpSubscriber;
import com.chen.palmar.common.widget.view.AutoTabLayout;
import com.chen.palmar.common.widget.view.AutoToolbar;
import com.chen.palmar.common.widget.view.CircleImageView;
import com.chen.palmar.entity.SelectProducerEntity;
import com.chen.palmar.entity.TagListEntity;
import com.chen.palmar.entity.TypeListEntity;
import com.primb.androidlibs.ui.recyclerview.BaseQuickAdapter;
import com.primb.androidlibs.ui.recyclerview.BaseViewHolder;
import com.primb.androidlibs.utils.DisplayUtils;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import butterknife.Bind;
import butterknife.OnClick;
import rx.Subscription;


/**
 * Created by chen on 2018/1/6.
 */

public class ProducerTypeActivity extends BaseActivity {
    @Bind(R.id.title_bar)
    TextView titleBar;
    @Bind(R.id.tv_top)
    TextView tvTop;
    @Bind(R.id.tool_bar)
    AutoToolbar toolBar;
    @Bind(R.id.rv_content)
    RecyclerView rvContent;
    @Bind(R.id.swipe_producer)
    SwipeRefreshLayout swipeProducer;
    @Bind(R.id.rv_menu)
    RecyclerView rvMenu;
    @Bind(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @Bind(R.id.tab_detail)
    AutoTabLayout tabDetail;
    @Bind(R.id.tv_producer_cancel)
    TextView tvProducerCancel;
    @Bind(R.id.tv_producer_sure)
    TextView tvProducerSure;
    private ActionBarDrawerToggle actionBarDrawerToggle;
    private BaseQuickAdapter<SelectProducerEntity.DataBean, BaseViewHolder> adapter;
    private List<SelectProducerEntity.DataBean> dataList = new ArrayList<>();
    private Set<String> labels = new HashSet<>();
    private BaseQuickAdapter<TagListEntity.DataBean, BaseViewHolder> adapterMenu;
    private SparseArray<Boolean> selectList = new SparseArray<>();
    private String info;
    private List<TypeListEntity.DataBean> beanList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    public void init() {
        toolBar.setNavigationOnClickListener(v -> ProducerTypeActivity.this.finish());

        info = getIntent().getStringExtra("info");
        int index = getIntent().getIntExtra("index", 0);

        beanList = ((List<TypeListEntity.DataBean>) getIntent().getSerializableExtra("list"));

        titleBar.setText(beanList.get(index).getName());

        for (int i = 0; i < beanList.size(); i++) {
            TabLayout.Tab tab = tabDetail.newTab();
            tab.setText(beanList.get(i).getName());
            if (index == i) {
                tabDetail.addTab(tab, true);
            } else {
                tabDetail.addTab(tab);
            }
        }

        tabDetail.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                titleBar.setText(tab.getText());
                info = beanList.get(tab.getPosition()).getCategoryId() + "";
                try {
                    getListData(false);
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("服务器数据格式异常");
                    swipeProducer.setRefreshing(false);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        try {
            getListData(false);
        } catch (Exception e) {
            e.printStackTrace();
            showToast("服务器数据格式异常");
            swipeProducer.setRefreshing(false);
        }

        swipeProducer.setOnRefreshListener(() -> {
            try {
                getListData(false);
            } catch (Exception e) {
                e.printStackTrace();
                showToast("服务器数据格式异常");
                swipeProducer.setRefreshing(false);
            }
        });

        swipeProducer.setColorSchemeColors(ContextCompat.getColor(this, android.R.color.holo_blue_bright), ContextCompat.getColor(ProducerTypeActivity.this, android.R.color.holo_green_light), ContextCompat.getColor(ProducerTypeActivity.this, android.R.color.holo_orange_light), ContextCompat.getColor(ProducerTypeActivity.this, android.R.color.holo_red_light));

        //开关指示器，必须是drawer的监听器
        //扩展该监听器以监听事件自身
        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_open, R.string.drawer_close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                // 更新选项菜单
                supportInvalidateOptionsMenu();
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                supportInvalidateOptionsMenu();
            }

            @Override
            public void onDrawerStateChanged(int newState) {
                super.onDrawerStateChanged(newState);
                supportInvalidateOptionsMenu();
            }
        };
        //为侧滑菜单绑定监听器
        drawerLayout.addDrawerListener(actionBarDrawerToggle);

        tvTop.setText("筛选");
        Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.supply_select_icon);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        tvTop.setCompoundDrawables(null, null, drawable, null);
        tvTop.setCompoundDrawablePadding(1);

        rvContent.setNestedScrollingEnabled(false);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvContent.setLayoutManager(linearLayoutManager);
        rvContent.setItemAnimator(new DefaultItemAnimator());
        adapter = new BaseQuickAdapter<SelectProducerEntity.DataBean, BaseViewHolder>(R.layout.item_type) {
            @Override
            protected void convert(BaseViewHolder helper, SelectProducerEntity.DataBean item) {
                helper.setText(R.id.tv_item_type_content, item.getDesc());
                helper.setText(R.id.tv_item_type_name, item.getName());
                CircleImageView head = (CircleImageView) helper.getView(R.id.iv_item_type_head);
                Picasso.with(ProducerTypeActivity.this).load(item.getLogo()).placeholder(R.mipmap.home_item_head_icon).error(R.mipmap.home_item_head_icon).into(head);
            }
        };
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            Intent intent = new Intent(ProducerTypeActivity.this, ProducerDetailActivity.class);
            intent.putExtra("info", adapter.getData().get(position).getFactoryId() + "");
            startActivity(intent);
        });
        rvContent.setAdapter(adapter);

        getTagList();

        GridLayoutManager layoutManager = new GridLayoutManager(ProducerTypeActivity.this, 3);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvMenu.setLayoutManager(layoutManager);
        rvMenu.setItemAnimator(new DefaultItemAnimator());

        adapterMenu = new BaseQuickAdapter<TagListEntity.DataBean, BaseViewHolder>(R.layout.item_supply_tag) {
            @Override
            protected void convert(BaseViewHolder helper, TagListEntity.DataBean item) {
                helper.setText(R.id.iv_item_supply_tag, item.toString());
                CheckBox box = (CheckBox) helper.getView(R.id.iv_item_supply_tag);
                box.setTextSize(DisplayUtils.dip2px(ProducerTypeActivity.this, 14f));
                if (selectList.get(helper.getAdapterPosition())) {
                    box.setChecked(true);
                    box.setTextColor(ContextCompat.getColor(ProducerTypeActivity.this, R.color.colorPrimaryDark));
                } else {
                    box.setTextColor(ContextCompat.getColor(ProducerTypeActivity.this, R.color.app_font));
                    box.setChecked(false);
                }
            }
        };
        adapterMenu.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                selectList.put(position, !selectList.get(position));
                for (int i = 0; i < selectList.size(); i++) {
                    if (selectList.get(i)) {
                        labels.add(adapterMenu.getData().get(position).getLabelId() + "");
                    } else {
                        labels.remove(adapterMenu.getData().get(position).getLabelId() + "");
                    }
                }
                adapterMenu.notifyDataSetChanged();
            }
        });
        rvMenu.setAdapter(adapterMenu);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_producer_type;
    }

    private void getTagList() {
        Subscription subscribe = DataCenter.tagListInfo().subscribe(new HttpSubscriber<TagListEntity>(this, null) {
            @Override
            public void onNext(TagListEntity tagListEntity) {
                for (int i = 0; i < tagListEntity.getData().size(); i++) {
                    selectList.put(i, false);
                }
                adapterMenu.setNewData(tagListEntity.getData());
            }
        });
        subscription.add(subscribe);
    }

    /**
     * 数据动态列表
     */
    private void getListData(boolean isLoad) {
        if (!isLoad) {
            swipeProducer.setRefreshing(true);
        }
        HashMap<String, Object> map = new HashMap<>();
        Iterator<String> iterator = labels.iterator();
        StringBuffer buffer = new StringBuffer();
        while (iterator.hasNext()) {
            if (labels.size() > 1) {
                buffer.append(iterator.next() + ",");
            } else {
                buffer.append(iterator.next());
            }
        }
        map.put("category_id", info);
        map.put("labels", buffer.toString());
        Subscription listSub = DataCenter.listProducerSelect(map).subscribe(new HttpSubscriber<SelectProducerEntity>(ProducerTypeActivity.this, null) {
            @Override
            public void onNext(SelectProducerEntity listEntity) {
                dataList.clear();
                dataList.addAll(listEntity.getData());
                adapter.setNewData(dataList);
                swipeProducer.setRefreshing(false);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                swipeProducer.setRefreshing(false);
            }
        });
        subscription.add(listSub);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //在更改任意配置时更新状态
        actionBarDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onPostCreate(savedInstanceState, persistentState);
        //在框架还原任意实例状态之后同步Drawer的状态
        actionBarDrawerToggle.syncState();
    }

    @OnClick({R.id.tv_top, R.id.tv_producer_cancel, R.id.tv_producer_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_top:
                if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
                    drawerLayout.post(() -> drawerLayout.closeDrawers());
                } else {
                    drawerLayout.post(() -> drawerLayout.openDrawer(Gravity.RIGHT));
                }
                break;
            case R.id.tv_producer_cancel:
                drawerLayout.post(() -> drawerLayout.closeDrawers());
                break;
            case R.id.tv_producer_sure:
                getListData(false);
                drawerLayout.post(() -> drawerLayout.closeDrawers());
                break;
        }
    }
}
